/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl.cmd;

import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.event.StartEvent;
import com.je.bpm.core.model.process.Process;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.core.model.task.KaiteUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.deploy.DeploymentManager;
import com.je.bpm.engine.impl.persistence.entity.MessageEventSubscriptionEntity;
import com.je.bpm.engine.impl.runtime.ProcessInstanceBuilderImpl;
import com.je.bpm.engine.impl.util.ProcessInstanceHelper;
import com.je.bpm.engine.repository.ProcessDefinition;
import com.je.bpm.engine.runtime.ProcessInstance;
import com.je.common.auth.AuthAccount;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;


public class SponsorProcessInstanceByMessageCmd implements Command<ProcessInstance> {

    protected String messageName;
    protected String businessKey;
    protected Map<String, Object> processVariables;
    protected Map<String, Object> transientVariables;
    protected String firstUser;
    protected String assigneeList;
    protected String tenantId;

    public SponsorProcessInstanceByMessageCmd(String messageName, String businessKey, Map<String, Object> processVariables, String tenantId) {
        this.messageName = messageName;
        this.businessKey = businessKey;
        this.processVariables = processVariables;
        this.tenantId = tenantId;
    }

    public SponsorProcessInstanceByMessageCmd(String messageName, String businessKey, String assignee, Map<String, Object> processVariables, String tenantId) {
        this.messageName = messageName;
        this.businessKey = businessKey;
        this.processVariables = processVariables;
        this.tenantId = tenantId;
        this.assigneeList = assignee;
    }

    public SponsorProcessInstanceByMessageCmd(String messageName, String businessKey, String firstUser, String assignee,
                                              Map<String, Object> processVariables, String tenantId) {
        this.messageName = messageName;
        this.businessKey = businessKey;
        this.processVariables = processVariables;
        this.tenantId = tenantId;
        this.firstUser = firstUser;
        this.assigneeList = assignee;
    }

    public SponsorProcessInstanceByMessageCmd(ProcessInstanceBuilderImpl processInstanceBuilder) {
        this.messageName = processInstanceBuilder.getMessageName();
        this.businessKey = processInstanceBuilder.getBusinessKey();
        this.processVariables = processInstanceBuilder.getVariables();
        this.transientVariables = processInstanceBuilder.getTransientVariables();
        this.tenantId = processInstanceBuilder.getTenantId();
        this.firstUser = processInstanceBuilder.getFirstUser();
    }

    @Override
    public ProcessInstance execute(CommandContext commandContext) {

        if (messageName == null) {
            throw new ActivitiIllegalArgumentException("Cannot start process instance by message: message name is null");
        }
        MessageEventSubscriptionEntity messageEventSubscription = commandContext.getEventSubscriptionEntityManager().findMessageStartEventSubscriptionByName(messageName, tenantId);
        if (messageEventSubscription == null) {
            throw new ActivitiObjectNotFoundException("Cannot start process instance by message: no subscription to message with name '" + messageName + "' found.", MessageEventSubscriptionEntity.class);
        }

        String processDefinitionId = messageEventSubscription.getConfiguration();
        if (processDefinitionId == null) {
            throw new ActivitiException("Cannot start process instance by message: subscription to message with name '" + messageName + "' is not a message start event.");
        }

        DeploymentManager deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentManager();
        ProcessDefinition processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
        if (processDefinition == null) {
            throw new ActivitiObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", ProcessDefinition.class);
        }

        //找到第一个和第二个节点的id
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(processDefinition.getId());
        Process mainProcess = bpmnModel.getMainProcess();
        StartEvent startEvent = (StartEvent) mainProcess.getInitialFlowElement();
        String firstTaskRef = startEvent.getOutgoingFlows().get(0).getTargetRef();
        //找到第一个任务节点
        KaiteBaseUserTask firstBaseUserTask = (KaiteBaseUserTask) bpmnModel.getFlowElement(firstTaskRef);
        if (!(firstBaseUserTask instanceof KaiteUserTask)) {
            throw new ActivitiException("Sponsor process only effective on the first task is KaiteUserTask.");
        }

        //获取第二个节点
        if (firstBaseUserTask.getOutgoingFlows().size() > 1) {
            throw new ActivitiException(String.format("Porcess %s can't sponsor because the first task's outgoing sequence flow only be 1.", processDefinition.getName()));
        }

        String secondTaskRef = firstBaseUserTask.getOutgoingFlows().get(0).getTargetRef();
        KaiteBaseUserTask secondBaseUserTask = (KaiteBaseUserTask) bpmnModel.getFlowElement(secondTaskRef);
        String firstTaskId = firstBaseUserTask.getId();
        String secondTaskId = secondBaseUserTask.getId();

        if (processVariables == null) {
            processVariables = new HashMap<>();
        }

        if (StringUtils.isEmpty(firstUser)) {
            AuthAccount activitiUser = Authentication.getAuthenticatedUser();
            if (activitiUser == null) {
                throw new ActivitiException("Can not get logined user from the context.");
            }
            firstUser = activitiUser.getDeptId();
        }

        if (transientVariables == null) {
            transientVariables = new HashMap<>();
        }
        commandContext.addAttribute(CommandContext.IS_SPONSOR, true);
        transientVariables.put(firstTaskId, firstUser);
        transientVariables.put(secondTaskId, assigneeList);

        ProcessInstanceHelper processInstanceHelper = commandContext.getProcessEngineConfiguration().getProcessInstanceHelper();
        ProcessInstance processInstance = processInstanceHelper.createAndStartProcessInstanceByMessage(processDefinition, businessKey, messageName, processVariables, transientVariables);
        return processInstance;
    }

}
